package com.runshu.newsmartark.dbutil;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.entity.CategoryListEntity;
import com.runshu.newsmartark.entity.ConfirmStockEntity;
import com.runshu.newsmartark.entity.HwInfoEntity;
import com.runshu.newsmartark.entity.InsertLogInfoEntity;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.model.BaseModel;
import com.runshu.newsmartark.network.netbean.HttpRequestParamsBuilder;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.network.netinterface.MyCallBack;
import com.runshu.newsmartark.util.LodDialogClass;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;
import com.runshu.newsmartark.util.y.sftp.SftpConfig;
import com.runshu.newsmartark.util.y.sftp.SftpUtil;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.runshu.newsmartark.common.ConstantUrl.Share_Category;
import static com.runshu.newsmartark.common.ConstantUrl.Share_Manufacturers;
import static com.runshu.newsmartark.common.ConstantUrl.Share_Modle;
import static com.runshu.newsmartark.common.ConstantUrl.Share_StockName;
import static com.runshu.newsmartark.common.ConstantUrl.Share_StockNum;

/**
 * Demo class
 *
 * @author yu
 * @date 12/9/20
 * @decs：
 */

public class RefreshUtils extends BaseModel {

    private static RefreshUtils instance;
    SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );

    public static RefreshUtils getInstance() {
        if (instance == null) {
            synchronized (RefreshUtils.class) {
                if (instance == null) {
                    instance = new RefreshUtils();
                }
            }
        }
        return instance;
    }

    public void refreshAll() {
        //刷新用户信息
        refreshUserinfo();
        //刷新所有产品信息
        refreshProAllInfo();
        //获取智能柜基本信息
        refreshCabinetInfo();
        //日志上传
        upLoadLog();
    }


    /**
     * allStock : 21
     * userName : 张三
     * office : 心内科
     * isAdd : true
     * stockChange : +8
     * allProducts : [{
     * "id":"","serialNo":"","productNo":"B.112.002.0018",
     * "productName":"造影导丝(InQwire)",
     * "productModel":"IQ35F180J3",
     * "batchNo":"K1768471","periodDate":"2023-01-23",
     * "createTime":"","remark":"",
     * "isStockWaring":0,"isPeriodWaring":0,
     * "manufacturer":"美国麦瑞通医疗设备有限公司","productTime":"
     * ","warnDateNumber":"","warnValue":"",
     * "stock":10,"inventoryStatus":"","hwName":""
     * ,"surplusDays":"","dataSource":0,"stockName":"","classification":"",
     * "company":"","productAttribute":"","registNo":"","storageCondition":"","number":""
     * ,"updateTime":"","hospitalId":"","isAdd":true,"stockChange":"+12"}
     * ,{"id":"","serialNo":"","productNo":"B.112.002.0018","productName":"测试耗材(InQwire)"
     * ,"productModel":"IQ35F180J3","batchNo":"K1768471","periodDate":"2023-01-23","createTime":"","remark":"","isStockWaring":0,"isPeriodWaring":0,"manufacturer":"美国麦瑞通医疗设备有限公司","productTime":"","warnDateNumber":"","warnValue":"","stock":11,"inventoryStatus":"","hwName":"","surplusDays":"","dataSource":0,"stockName":"","classification":"","company":"","productAttribute":"","registNo":"","storageCondition":"","number":"","updateTime":"","hospitalId":"","isAdd":false,"stockChange":"-3"}]
     */
    List<ProAllEntity> nowPro;
    List<OperRecordfEntity> records;
    List<ProAllEntity> menProAllList;

    public ConfirmStockEntity getGoodsExchange(String[] lists) {
        ConfirmStockEntity result = new ConfirmStockEntity();
        //新增商品
        nowPro = DBUtils.getInstance().getProBySerialNos( lists );
        List<ProAllEntity> noRecoGoods = new ArrayList<>();
        List<String> list = new ArrayList<>();
        if (lists != null && nowPro != null) {
            for (ProAllEntity tmp : nowPro) {
                list.add( tmp.getSerialNo() );
            }
            for (String tmp : lists) {
                if (!list.contains( tmp )) {
                    noRecoGoods.add( new ProAllEntity( tmp ) );
                }
            }
            nowPro.addAll( noRecoGoods );
        }
        DBUtils.getInstance().getProAllDao().insertAllProIgnore( noRecoGoods );
        //老商品
        List<ProAllEntity> oldPro = DBUtils.getInstance().getProAllDao().getSelfProList();
        StringBuilder stringBuilder = new StringBuilder();
        for (String str : lists) {
            stringBuilder.append( str + "," );
        }
        Log.e( "yby", stringBuilder.toString() );
        if (oldPro == null) oldPro = new ArrayList<>();
        int nowNum = nowPro == null ? 0 : nowPro.size();
        int oldNum = oldPro == null ? 0 : oldPro.size();
        List<ProAllEntity> addPro = new ArrayList<>();
        for (ProAllEntity now : oldPro) {
            boolean isContinue = false;
            for (ProAllEntity old : nowPro) {
                if (now.getSerialNo().equals( old.getSerialNo() )) {
                    isContinue = true;
                    break;
                }
            }
            if (isContinue) continue;
            addPro.add( now );
        }
        Log.w( "yby", addPro.toString() );
        Map<String, ProAllEntity> addMap = new HashMap<>();
        //减少/增加的项
        List<ConfirmStockEntity.AllProductsBean> menProBean = DBUtils.getInstance().getMenusPros( lists );
        List<ConfirmStockEntity.AllProductsBean> addProBean = DBUtils.getInstance().getAddPros( lists );
        //添加操作记录
        List<ProAllEntity> addProAllList = DBUtils.getInstance().getProAllDao().getAddProAllList( lists );
        List<ProAllEntity> menProAllList = DBUtils.getInstance().getProAllDao().getMenusProAllList( lists );
        records = new ArrayList<>();
        String createTime = sdf.format( new Date() );
        UserInfoEntity userInfoGlob = MyApplication.getUserInfoGlob();
        String usercode = userInfoGlob == null ? "" : String.valueOf( userInfoGlob.getId() );
        //领取  //type 0上架 1领取 2归还
        if (menProAllList != null && menProAllList.size() > 0) {
            for (ProAllEntity tmp : menProAllList) {
                records.add( new OperRecordfEntity( createTime, tmp.getSerialNo(), tmp.getProductName(), 1, usercode ) );
            }
        }
        //上架或归还
        List<String> plusId = new ArrayList<>();
        Map<String, String> backSeri = new HashMap<>();
        if (addProAllList != null && addProAllList.size() != 0) {
            for (ProAllEntity tmp : addProAllList) {
                plusId.add( tmp.getSerialNo() );
            }
            List<ProAllEntity> addGoods = DBUtils.getInstance().getProBySerialNos( plusId.toArray( new String[plusId.size()] ) );
            if (addGoods != null && addGoods.size() > 0) {
                for (ProAllEntity tmp : addGoods) {
                    if (usercode.equals( tmp.getOperateUser() )) {
                        backSeri.put( tmp.getSerialNo(), tmp.getSerialNo() );
                    }
                }
            }
            for (ProAllEntity tmp : addProAllList) {
                records.add( new OperRecordfEntity( createTime, tmp.getSerialNo(), tmp.getProductName(),
                        backSeri.containsKey( tmp.getSerialNo() ) ? 2 : 0
                        , usercode ) );
            }
        }
        //更新减少项的操作人
        this.menProAllList = menProAllList;
        NLogUtil.i( NLogUtil.INFO_Operate_SerNoGoods,"{\"本次增加货物\","+new Gson().toJson( addProAllList )+"}"
                +"{\"本次减少货物\","+new Gson().toJson( menProAllList )+"}" );
        //新增项
        ArrayList<ConfirmStockEntity.AllProductsBean> allProducts = new ArrayList<>();
        allProducts.addAll( addProBean );
        allProducts.addAll( menProBean );

        result.setAllProducts( allProducts );
        result.setUserName( MyApplication.getUserInfoGlob().getUsername() );
        result.setOffice( MyApplication.getUserInfoGlob().getOffice() );
        result.setAllStock( nowNum );
        result.setStockChange( ((nowNum - oldNum) > 0 ? "+" : "") + String.valueOf( nowNum - oldNum ) );
        //将产品插入  本柜产品表
//        DBUtils.getInstance().insertSelfProList( nowPro );
//        refreshSelfProListAndRecord();
        return result;
    }

    private void updateMenus() {
        if (menProAllList != null && menProAllList.size() != 0) {
            UserInfoEntity userInfoGlob = MyApplication.getUserInfoGlob();
            String usercode = userInfoGlob == null ? "" : String.valueOf( userInfoGlob.getId() );
            if (menProAllList != null && menProAllList.size() != 0) {
                for (ProAllEntity tmp : menProAllList) {
                    tmp.setOperateUser( usercode );
                }
                DBUtils.getInstance().getProAllDao().insertAllPro( menProAllList );
            }
        }
        menProAllList = null;
    }

    /**
     * 更新本次操作数据库
     */
    public void refreshSelfProListAndRecord() {
        SharedPreferencesUtils.put( MyApplication.getApplication(), Share_StockNum, String.valueOf( nowPro.size() ) );
        new Thread( new Runnable() {
            @Override
            public void run() {

                if (nowPro != null) {
                    DBUtils.getInstance().insertSelfProList( nowPro );


                }
                if (records != null) {
                    DBUtils.getInstance().getProAllDao().insertOperRecords( records );
                }
                updateMenus();
                nowPro = null;
                records = null;
                //上传日志数据
                RefreshUtils.getInstance().insertHardwareLog( null );
            }
        } ).start();
    }

    //获取用户基本数据
    public void refreshUserinfo() {
        HttpRequestParamsBuilder builder = new HttpRequestParamsBuilder();
        super.initDataFromServer( ConstantUrl.GET_UserInfo, builder.build(), UserInfoEntity.class, ResponseBean.RES_DATATYPE_BEANLIST, new MyCallBack() {
            @Override
            public void onSuccess(ResponseBean data) {
                new Thread( new Runnable() {
                    @Override
                    public void run() {
                        List<UserInfoEntity> userInfoListdata = (List<UserInfoEntity>) data.pullData();
                        if (userInfoListdata != null && userInfoListdata.size() > 0) {
                            DBUtils.getInstance().deleteAllUserInfo();
                            DBUtils.getInstance().insertUserList( userInfoListdata );
                        }

                        LogUtil.e( "数据库", DBUtils.getInstance().getUserList().toString() );

                    }
                } ).start();
            }

            @Override
            public void onError(ResponseBean data) {

                ToastUtils.showText( data.getMessage() );

            }
        } );

    }

    //刷新所有医院商品

    public void refreshProAllInfo() {
        SharedPreferencesUtils.put( MyApplication.getApplication(), ConstantUrl.Share_RefreshProTime, sdf.format( new Date() ) );
        new Thread( new Runnable() {
            @Override
            public void run() {
                HttpRequestParamsBuilder builder = new HttpRequestParamsBuilder();
                builder.putParams( "updateTime", DBUtils.getInstance().getLastUpdateTime() );
                RefreshUtils.this.initDataFromServer( ConstantUrl.GET_AllProInfo, builder.build(), ProAllEntity.class, ResponseBean.RES_DATATYPE_BEANLIST, new MyCallBack() {
                    @Override
                    public void onSuccess(ResponseBean data) {
                        new Thread( new Runnable() {
                            @Override
                            public void run() {
                                List<ProAllEntity> allList = (List<ProAllEntity>) data.pullData();
                                if (allList != null) {
                                    DBUtils.getInstance().insertAllProList( allList );
                                }
                                SharedPreferencesUtils.put( MyApplication.getApplication(), ConstantUrl.Share_LoadingFirst, false );
                                //刷新医院商品
                                List<String> serialNo = DBUtils.getInstance().getProAllDao().getSerialNo();
                                if (allList != null && allList.size() != 0) {
                                    List<ProSelfEntity> proBySerialNos = DBUtils.getInstance().getProAllDao().getProBySerialNosToSelfEntity( serialNo.toArray( new String[serialNo.size()] ) );
                                    DBUtils.getInstance().getProAllDao().insertSelfPro( proBySerialNos );
                                }

                            }
                        } ).start();
                        LodDialogClass.closeCustomCircleProgressDialog();
                    }

                    @Override
                    public void onError(ResponseBean data) {
//                        ToastUtils.showText( data.getMessage() );
                        LodDialogClass.closeCustomCircleProgressDialog();
                    }
                } );
            }
        } ).start();
    }


    /**
     * 获取柜子的基本信息
     */
    public void refreshCabinetInfo() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                HttpRequestParamsBuilder builder = new HttpRequestParamsBuilder();
                RefreshUtils.this.initDataFromServer( ConstantUrl.GET_HardwareInfo, builder.build(), HwInfoEntity.class, ResponseBean.RES_DATATYPE_BEAN, new MyCallBack() {
                    @Override
                    public void onSuccess(ResponseBean data) {
                        new Thread( new Runnable() {
                            @Override
                            public void run() {
                                HwInfoEntity hwInfoEntity = (HwInfoEntity) data.pullData();
                                SharedPreferencesUtils.put( MyApplication.getApplication(), Share_StockName, hwInfoEntity.getHwName() );
                            }
                        } ).start();
                    }

                    @Override
                    public void onError(ResponseBean data) {
                        ToastUtils.showText( data.getMessage() );
                    }
                } );
            }
        } ).start();
    }

    /**
     * 插入日志
     */
    public void insertHardwareLog(MyCallBack listener) {

        new Thread( new Runnable() {
            @Override
            public void run() {
                HttpRequestParamsBuilder builder = new HttpRequestParamsBuilder();
                List<OperRecordfEntity> logListInfo = DBUtils.getInstance().proAllDao.getLogListInfo();
                if (logListInfo == null || logListInfo.size() == 0) {
                    EventBusUtils.sendEvent( new Event( EventCode.EventRefreshNum ) );
                    if (listener != null)
                        listener.onError( new ResponseBean() );
                    return;
                }
                List<String> serialNo = DBUtils.getInstance().proAllDao.getSerialNo();
                builder.putParams( "logList", new InsertLogInfoEntity.LogList( MacUtils.getFormatMacAddr(), logListInfo ) );
                builder.putParams( "cabinetSerialNoList", new InsertLogInfoEntity.CabinetSerialNoList( MacUtils.getFormatMacAddr(), serialNo ) );
                RefreshUtils.this.initDataFromServer( ConstantUrl.INSERT_HardwareLog, builder.build(), ResponseBean.class, ResponseBean.RES_DATATYPE_BEAN, new MyCallBack() {

                    @Override
                    public void onSuccess(ResponseBean data) {
                        SharedPreferencesUtils.put( MyApplication.getApplication(), ConstantUrl.Share_RefreshTime, sdf.format( new Date() ) );
                        new Thread( new Runnable() {
                            @Override
                            public void run() {
                                if (logListInfo != null && logListInfo.size() > 0)
                                    DBUtils.getInstance().proAllDao.deleteOpearInfo( logListInfo );
                            }
                        } ).start();
                        if (listener != null)
                            listener.onSuccess( data );
                        EventBusUtils.sendEvent( new Event( EventCode.EventRefreshNum ) );
                    }

                    @Override
                    public void onError(ResponseBean data) {

                        if (listener != null)
                            listener.onError( data );
                        ToastUtils.showText( data.getMessage() );
                    }
                } );
            }
        } ).start();
    }

    /**
     * 心跳检测
     */
    public void HWHeart() {
        HttpRequestParamsBuilder builder = new HttpRequestParamsBuilder();
        builder.putParams( "macAddress", MacUtils.getFormatMacAddr() );
        RefreshUtils.this.initDataFromServer( ConstantUrl.HW_HEART, builder.build(), ResponseBean.class, ResponseBean.RES_DATATYPE_BEAN, new MyCallBack() {
            @Override
            public void onSuccess(ResponseBean data) {
            }

            @Override
            public void onError(ResponseBean data) {
                ToastUtils.showText( data.getMessage() );
            }
        } );
    }

    public void upLoadLog() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                SftpUtil.upload( new SftpConfig(), "/data/smart_box", NLogUtil.LogFileName, MyApplication.getApplication().getFilesDir().getPath() );
            }
        } ).start();
    }

}